package jfuzzyprincepless.zarchive.algorithm.structure;

import java.util.*;

import jfuzzyprincepless.negotiation.IExecutionContext;
import jfuzzyprincepless.zarchive.negotiation.ZArchNegotiationUtils;

/**
 * runs all commands in chain;
 * returns last result or null if commands.length == 0
 */
public class ChainCommand // TODO: rename 2 compound
	extends BaseNegotiationConstruction
	implements IMultiConstruction
{
	private List<ICommandConstruction> commands =
		new ArrayList<ICommandConstruction>();

	public ChainCommand(List<ICommandConstruction> commands) {
		// XXX: silent creation of new ArrayList<INegotiatingAgent> in super
		this.commands = commands;
	}

	public ChainCommand(ICommandConstruction ... commands) {
		this(
			new ArrayList<ICommandConstruction>(
				Arrays.asList(commands)
			)
		);
	}

	@Override
	public void execute(IExecutionContext context) {
		executeCmdList(commands, context);
	}

	@Override
	public List<ICommandConstruction> getCommandsList() {
		return commands;
	}

	@Override
	public void extractAgentsFromConstructions() {
		agents = ZArchNegotiationUtils.extractAgents(commands);
	}

	public static void executeCmdList(
		List<? extends ICommandConstruction> commands,
		IExecutionContext context
	) {
		for (ICommandConstruction command : commands) {
			command.execute(context);
		}
	}
}
